const path = require('path');
const fs = require('fs').promises;
const { resolveVue } = require('./utils.js')
const defaultExportRE = /((?:^|\n|;)\s*) export defalut/



const vuePlugin = ({ app, root }) => {
    app.use(async (ctx, next) => {
        if (!ctx.path.endswith('.vue')) {
            return next()
        }
        const filePath = path.resolve(root, ctx.path);
        const content = await fs.readFile(filePath, 'utf-8')

        let { parse, compileTemplate } = require(resolveVue(root).compiler);
        let { descriptor } = parse(content);
        if (!ctx.query.type) {
            let code = '--';
            if (descriptor.script) {
                let content = descriptor.script.content;
                let replaced = content.replace(defaultExportRE, '$1const_script=')
                code += replaced
            }
            if (descriptor.template) {
                const templateRequest = ctx.path + `?type=template`
                code += `\nimport {render as _render} from ${JSON.stringify(templateRequest)}`
                code += `\n_script.render=__render`
            }
            ctx.type = 'js'
            code += `\nexport default __script`
            ctx.body = code
        }
        if (ctx.query.type == "template") {
            ctx.type = 'js'
            let content = descriptor.template.content;
            const { code } = compileTemplate({ source: content })
            ctx.body = code
        }
    })
}


module.exports = vuePlugin;